﻿/* ---------------------------

  主逻辑JS
  负责启动各函数渲染主页面
  爸爸到此一游
---------------------------- */

var pre_height = 0;
var cur_height = 0;

$(document).ready(function(){
    set_state();
    set_chain_blocks(1);
    set_homepage_numbers();

    set_echart_1_type();
    set_echart_2_3();
    set_echart_4();

    get_local_node();


    setInterval(hook, 5000);

})


// 需要动态更新的放入钩子里
function hook() {
    get_height();

    if(pre_height !== cur_height) {
        set_state();
        set_chain_blocks(0);
        set_homepage_numbers();
        set_echart_1_type();
        set_echart_2_3();
        set_echart_4();

        pre_height = cur_height;
    }
}


function set_echart_1_type() {

    let data = [];

    function set_echart_1_type_callback(data) {
        let chartDom = document.getElementById('echart1');
        let myChart = echarts.init(chartDom, 'dark');
        let option;

        option = {
          // backgroundColor: 'none',
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: '5%',
            top: 'center',
          },
          series: [
            {
              // color: ['#065aab', '#066eab', '#0682ab', '#0696ab', '#06a0ab','#06b4ab','#06c8ab','#06dcab','#06f0ab'],
              name: '类型占比',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '40',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: data
              // [
              //   { value: 1048, name: 'Search Engine' },
              //   { value: 735, name: 'Direct' },
              //   { value: 580, name: 'Email' },
              //   { value: 484, name: 'Union Ads' },
              //   { value: 300, name: 'Video Ads' }
              // ]
            }
          ]
        };

        option && myChart.setOption(option);
    }

    function get_upload_num_callback(num) {
        data.push({name: 'upload', value: num});
        ask_type_num('request', get_request_num_callback);
    }
    function get_request_num_callback(num) {
        data.push({name: 'request', value: num});
        ask_type_num('share', get_share_num_callback);
    }
    function get_share_num_callback(num) {
        data.push({name: 'share', value: num});
        ask_type_num('evaluate', get_evaluate_num_callback);
    }
    function get_evaluate_num_callback(num) {
        data.push({name: 'evaluate', value: num});
        set_echart_1_type_callback(data)
    }

    ask_type_num('upload', get_upload_num_callback);
}


function set_echart_2_3() {

    function get_local_node_address_callback(address_state, address) {

        $.ajax({
            type: "POST",
            url: "./ask_global_cnrp",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({'height_list': [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]}),
            dataType: "json",
            success: function (message) {
                if (message.state === 0) {
                    let height_list = message.content.height;
                    let cnrp_list = message.content.cnrp;

                    let cnrp_max = [];
                    let cnrp_local =[];
                    let cnrp_mean = [];
                    let cnrp_min = [];

                    let list_length = height_list.length;
                    for(let i = 0; i < list_length; i++) {
                        let target_dict = cnrp_list[i];
                        // console.log(address);
                        // console.log(target_dict.address);
                        if(target_dict[address] === undefined) {
                            cnrp_local.push(0);
                        }
                        else {
                            cnrp_local.push(target_dict[address]);
                        }

                        let v_max = 0;
                        let v_min = 1.1;
                        let v_total = 0;

                        let j = 0;
                        for(let k in target_dict) {
                            let target_v = target_dict[k];
                            v_total += target_v;
                            if(target_v > v_max) {
                                v_max = target_v;
                            }
                            if(target_v < v_min) {
                                v_min = target_v;
                            }
                            j += 1;
                        }
                        cnrp_max.push(v_max);
                        cnrp_min.push(v_min);
                        cnrp_mean.push((v_total/j).toFixed(3));

                        if(i===list_length-1) {

                            let axis_address_temp = Object.keys(target_dict).sort(function(a,b){return target_dict[b]-target_dict[a]});

                            let axis_address = [];

                            let axis_temp_length = axis_address_temp.length;

                            if(axis_temp_length > 10) {

                                axis_address = axis_address_temp.slice(0,8);
                                axis_address.push(axis_address_temp[axis_temp_length-2]);
                                axis_address.push(axis_address_temp[axis_temp_length-1]);

                                // let a_group = Math.ceil(axis_temp_length/12);
                                // let a_acc = a_group;
                                // for(let s = 0; s < axis_temp_length; s++) {
                                //     if(a_acc >= a_group) {
                                //         axis_address.push(axis_address_temp[s]);
                                //         a_acc = 1;
                                //     }
                                //     else {
                                //         a_acc += 1;
                                //     }
                                // }
                            }
                            else {
                                axis_address = axis_address_temp;
                            }

                            let cnrp_list = [];
                            // let address_list = [];
                            let s_length = axis_address.length;
                            for(let s=0; s<s_length; s++) {
                                cnrp_list.push(target_dict[axis_address[s]]);
                                // address_list.push(axis_address[s].slice(0, 4))
                            }

                            set_echart_3_cnrp_node(address, cnrp_local[list_length-1], axis_address, cnrp_list);

                            // set_echart_4(target_dict);
                            // console.log(target_dict);
                        }

                    }

                    // console.log(height_list)
                    // console.log(cnrp_list)

                    set_echart_2_cnrp_height(height_list, cnrp_max, cnrp_local, cnrp_mean, cnrp_min);

                }

                if(message.state===-1) {

                }
            },
            error: function (message) {

            }
        });

    }

    // 挂起 主进程
    get_local_node(get_local_node_address_callback);

}


function set_echart_4(globle_cnrp_dict=undefined) {
     $.ajax({
         type: "GET",
         url: "./get_local_cnrp",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (message) {
             if(message.state===0) {
                 let local_cnrp_dict = message.content;
                 let axis_x = [];
                 let axis_y = [];
                 let n = 0;
                 for(let k in local_cnrp_dict) {
                     axis_x.push(k);
                     axis_y.push(local_cnrp_dict[k]);
                     n += 1;
                     if(n === 10) {
                         break;
                     }
                 }
                 set_echart_4_local_cnrp(axis_x, axis_y);
             }
             if(message.state===-1) {
                 $('#echart6').html('<div class="blank-line-01"></div><div class="container"><div class="row text-center text-white console-text-size-02">未创建本地节点</div></div>');
             }

         }
     });

}


function set_echart_2_cnrp_height(axis_height, cnrp_max, cnrp_local, cnrp_mean, cnrp_min) {

    let y_range = [0, 1.1];
    let list_length = axis_height.length;
    for(let i = 0; i < list_length; i++) {
        if(cnrp_max[i]>y_range[0]){
            y_range[0] = cnrp_max[i];
        }
        if(cnrp_min[i]<y_range[1]){
            y_range[1] = cnrp_min[i];
        }
    }

    let chartDom = document.getElementById('echart4');
    let myChart = echarts.init(chartDom, 'dark');
    let option;

    option = {
      // backgroundColor: 'none',
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['Max Rp', 'Local Rp', 'Mean Rp', 'Min Rp']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: axis_height
      },
      yAxis: {
        type: 'value',
        min: y_range[1],
        max: y_range[0],
      },
      series: [
        {
          name: 'Max Rp',
          type: 'line',
          smooth: true,
          // stack: 'Total',
          data: cnrp_max
        },
        {
          name: 'Local Rp',
          type: 'line',
          smooth: true,
          // stack: 'Total',
          data: cnrp_local
        },
        {
          name: 'Mean Rp',
          type: 'line',
            smooth: true,
          // stack: 'Total',
          data: cnrp_mean
        },
        {
          name: 'Min Rp',
          type: 'line',
            smooth: true,
          // stack: 'Total',
          data: cnrp_min
        }
      ]
    };

    option && myChart.setOption(option);

}


function set_echart_3_cnrp_node(local_address, local_rp, axis_address, cnrp_list) {
    let chartDom = document.getElementById('echart5');
    let myChart = echarts.init(chartDom, 'dark');

    let option;

    if(local_rp!==0) {
        axis_address.unshift(local_address);
        cnrp_list.unshift({value: local_rp, itemStyle: {color: '#fc97af'}});
    }

    // console.log(axis_address);
    // console.log(cnrp_list);

    // axis_address.push(local_address);
    // cnrp_list.unshift({value: local_rp, itemStyle: {color: '#fc97af'}});

    option = {
      tooltip: {
        trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
      grid: {
            left: '0%',
            top:'10px',
            right: '0%',
            bottom: '2%',
           containLabel: true
        },
      xAxis: {
          axisLabel: {
              formatter: function (value, index) {
                    // return value.slice(0, 4);
                  return ''+index;
                },
              align: 'center'
            },
        type: 'category',
        data: axis_address
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: cnrp_list,
          type: 'bar',
            barWidth:'50%',
            itemStyle: {
            normal: {
                color:'#2f89cf',
                opacity: 1,
				barBorderRadius: 5,
            }
        }
        }
      ]
    };

    option && myChart.setOption(option);

}


function set_echart_4_local_cnrp(axis_x_list, axis_y_list) {
    let chartDom = document.getElementById('echart6');
    let myChart = echarts.init(chartDom, 'dark');
    let option;

    option = {
      tooltip: {
        trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
      grid: {
            left: '0%',
            top:'10px',
            right: '0%',
            bottom: '2%',
           containLabel: true
        },
      xAxis: {
        type: 'category',
        axisLabel: {
              formatter: function (value, index) {
                    return value.slice(0, 4);
                },
              align: 'center'
            },
        data: axis_x_list
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: axis_y_list,
          type: 'bar',
            barWidth:'35%',
            itemStyle: {
            normal: {
                color:'#2f89cf',
                opacity: 1,
				barBorderRadius: 5,
            }
        }
        }
      ]
    };

    option && myChart.setOption(option);

}


function set_homepage_numbers() {
    function set_height_callback(num){
        num = '' + num;
        if(num.length < 4) {
            num = '0'.repeat(4-num.length) + num;
        }
        $('#homepage-middle-numbers-height').text(num);
    }

    function set_upload_num_callback(num){
        num = '' + num;
        if(num.length < 4) {
            num = '0'.repeat(4-num.length) + num;
        }
        $('#homepage-middle-numbers-data-num').text(num);
    }

    function set_global_cnrp_mean_callback(cnrp_dict){
        cnrp_dict = cnrp_dict.cnrp[0]

        let total = 0;
        let i = 0
        for(let k in cnrp_dict){
            total += cnrp_dict[k];
            i += 1;
        }
        i = '' + i;
        if(i.length < 4) {
            i = '0'.repeat(4-i.length) + i;
        }
        $('#homepage-middle-numbers-nodes-num').text(i);
        $('#homepage-middle-numbers-cnrp-mean').text(''+(total/i).toFixed(3));
    }


    get_height(set_height_callback);

    ask_type_num('upload', set_upload_num_callback);

    ask_global_cnrp(-1, set_global_cnrp_mean_callback);

}


function get_height(callback=null) {
    $.ajax({
        type: "GET",
        url: "./get_height",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(message) {
            cur_height = message.content.height;
            if(callback){
                callback(message.content.height);
            }
        },
        error: function(message) {

        }
    })
}


function set_state() {
    $.ajax({
        type: "GET",
        url: "./get_state",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(message) {
            var head_state = '';
            head_state += ' | Cur-height: ' + message.content.height;
            head_state += ' | Cur-nodes-num: ' + message.content.num_node;
            head_state += ' | Add-time: ' + message.content.block.tx_time;
            head_state += ' | Add-source: ' + message.content.block.node_address;
            head_state += ' | Updated e5s';
            $('#head-state').text('State: OK' + head_state);
        },
        error: function(message) {

        }
    })
}


// mode 为工作模式 0为前向更新 更新最新块 1为后向更新 更新以前的块
function set_chain_blocks(mode) {

    let post_msg = {'mode': mode, 'range': $('#id-side-panel-2-list').attr('title')}

    $.ajax({
    type: "POST",
    url: "./ask_chain",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(post_msg),
    dataType: "json",
    success: function(message) {
        let blocks_dict = message.content;
        let container_ele = $('#id-side-panel-2-list');

        if(message.state === 0) {
            // 前向更新 更新 new blocks
            if(mode===0) {
                let i = 0;
                for(let k in blocks_dict ){
                    let block = blocks_dict[k]
                    container_ele.prepend(
                        '<li class="time-line-item" onclick="pop_chain_block_detail(this)"><div class="lzc_icon"></div><div class="lzc_label" data-scroll-reveal="enter right over 1s" >' +
                        '<div class="side-panel-2-list-padding-right side-panel-2-list-padding-right-height-flag">Height: ' + block.height + ' ' + block.tx_type + ' ' + block.tx_time + '</div>' +
                        '<div class="side-panel-2-list-padding-right">' + 'Source: ' + block.node_address + '</div>' +
                        '<div class="side-panel-2-list-padding-right">' + 'Hash: ' + block.block_hash + '</div>' +
                        '</div></li>'
                    );
                    i += 1;
                }
                let pre_range = container_ele.attr('title').split(',')[1];
                container_ele.attr('title', pre_range + ',' + blocks_dict[''+i].height);
            }
            // 后向更新 更新历史 block
            if(mode===1) {

                let i = 0;
                for(let k in blocks_dict ){
                    let block = blocks_dict[k]
                    container_ele.append(
                        '<li class="time-line-item" onclick="pop_chain_block_detail(this)"><div class="lzc_icon"></div><div class="lzc_label" data-scroll-reveal="enter right over 1s" >' +
                        '<div class="side-panel-2-list-padding-right side-panel-2-list-padding-right-height-flag">Height: ' + block.height + ' ' + block.tx_type + ' ' + block.tx_time + '</div>' +
                        '<div class="side-panel-2-list-padding-right">' + 'Source: ' + block.node_address + '</div>' +
                        '<div class="side-panel-2-list-padding-right">' + 'Hash: ' + block.block_hash + '</div>' +
                        '</div></li>'
                    );
                    i += 1;
                }
                let pre_range = container_ele.attr('title').split(',')[0];
                container_ele.attr('title', blocks_dict[''+i].height + ',' + pre_range)
            }
            let height_flag_ele = $('.side-panel-2-list-padding-right-height-flag');
            let range_end = height_flag_ele.first().text().split(' ')[1];
            let range_beg = height_flag_ele.last().text().split(' ')[1];
            container_ele.attr('title', range_beg+','+range_end);
        }

        if(message.state === -1) {

        }

    },
    error: function(message) {

    }
  });
}


function loading_gif(ele) {
    ele.html('<div class="blank-line-3"></div><div class="text-center"><img src="/static/picture/loading.gif" style="width: 30px" alt="loading..."></div>');
}


function good_gif(ele, add_html) {
    ele.html('<div class="blank-line-2"></div><div class="text-center"><img src="/static/picture/good.gif" style="width: 60px" alt="good"><div class="blank-line-1"></div>'+ add_html +'</div>');
}


function open_console() {$("#id-console-wrap-lc").fadeIn();}
function close_console() {$("#id-console-wrap-lc").fadeOut();}
function close_block_detail_panel() {$('#block-detail-panel-lc').fadeOut();}


function get_local_node(callback=null) {

    loading_gif($('#pills-1'));

    setTimeout(function () {

        $.ajax({
        type: "GET",
        url: "./get_local_node",
        contentType: "application/json; charset=utf-8",
        // data: JSON.stringify(post_msg),
        dataType: "json",
        success: function(message) {

            let container_ele = $('#pills-1');

            if (message.state === -1) {
                container_ele.html('<div class="row"><div class="blank-line-2"></div><div class="col-12"><div class="lead text-center console-text-size-025">当前未创建本地节点，不能进行发布操作，仅可查询</div><div class="blank-line-03"></div>' +
                    '<div class="text-center"><button type="button" class="btn btn-outline-primary console-content-btn-sm" onclick="get_create_node()">创建本地节点</button></div></div></div>')
                if(callback) {
                    callback(-1, 'no address');
                }
            }

            if (message.state === 0) {

                let node_info_dict = message.content;

                let content_html_wrap_s = '<div class="blank-line-02"></div>\n' +
                    '      <div class="text-center lead console-text-size-04">当前本地节点信息</div>\n' +
                    '      <div class="blank-line-01"></div>\n';

                let content_html_wrap_e = '<div class="blank-line-05"></div><div class="text-center"><button type="button" class="btn btn-outline-danger console-content-btn-sm" onclick="get_delete_node()" style="margin-right: 5px">删除本地节点</button>' +
                            '<button type="button" class="btn btn-outline-primary console-content-btn-sm" onclick="get_local_node()" style="margin-left: 5px">更新节点信息</button></div><div class="blank-line-1"></div>';

                container_ele.html(content_html_wrap_s + get_block_detail_tables_do(node_info_dict) + content_html_wrap_e);
                if(callback) {
                    callback(0, message.content.node_address);
                }
            }
        },
        error: function(message) {

        }
      });

    }, 1000);

}


function get_create_node() {

    loading_gif($('#pills-1'));

    setTimeout(function () {

        $.ajax({
            type: "GET",
            url: "./get_create_node",
            contentType: "application/json; charset=utf-8",
            // data: JSON.stringify(post_msg),
            dataType: "json",
            success: function (message) {

                if (message.state === 0) {
                    get_local_node();
                }
            },
            error: function (message) {

            }
        });

    }, 500);

}


function get_delete_node() {

    let confirm_info = confirm('警告：删除节点后您将永远失去所有已发布块的控制权。');
    if (confirm_info === false) {
        return
    }


    loading_gif($('#pills-1'));

    setTimeout(function () {

        $.ajax({
            type: "GET",
            url: "./get_delete_node",
            contentType: "application/json; charset=utf-8",
            // data: JSON.stringify(post_msg),
            dataType: "json",
            success: function (message) {

                if (message.state === 0) {
                    $('#pills-1').html('<div class="row"><div class="blank-line-2"></div><div class="col-12"><div class="lead text-center console-text-size-03">当前未创建本地节点，不能进行发布操作，仅可查询</div><div class="blank-line-03"></div>' +
                    '<div class="text-center"><button type="button" class="btn btn-outline-primary console-content-btn-bg" onclick="get_create_node()">创建本地节点</button></div></div></div>')

                }
            },
            error: function (message) {

            }
        });

    }, 500);
}


function query() {

    loading_gif($('#console-find-query-res-wrap'));

    let condition_dict_type_array = [];

    let condition_upload_ele = $('#console-find-input-type-upload');
    let condition_request_ele = $('#console-find-input-type-request');
    let condition_share_ele = $('#console-find-input-type-share');
    let condition_evaluate_ele = $('#console-find-input-type-evaluate');

    if (condition_upload_ele.prop('checked')) {
        condition_dict_type_array.push(condition_upload_ele.val())
    }
    if (condition_request_ele.prop('checked')) {
        condition_dict_type_array.push(condition_request_ele.val())
    }
    if (condition_share_ele.prop('checked')) {
        condition_dict_type_array.push(condition_share_ele.val())
    }
    if (condition_evaluate_ele.prop('checked')) {
        condition_dict_type_array.push(condition_evaluate_ele.val())
    }

    let condition_dict = {
        'block_info_type': 0,
        'find_condition': {
            'height': $('#console-find-input-height').val(),
            'block_hash': $('#console-find-input-block-hash').val(),
            'tx_id': $('#console-find-input-tx-id').val(),
            'business_id': $('#console-find-input-business-id').val(),
            'node_address': $('#console-find-input-node-address').val(),
            'subject': $('#console-find-input-subject').val(),
            'tx_type': condition_dict_type_array,
            'data_id': $('#console-find-input-data-id').val()
        }
    }

    setTimeout(function () {

        $.ajax({
            type: "POST",
            url: "./ask_query",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(condition_dict),
            dataType: "json",
            success: function (message) {

                if (message.state === 0) {

                    let blocks_dict = message.content;

                    let query_res_html = '<div class="col-12 console-content-padding-10">\n' +
                    '          <table class="table table-hover">\n' +
                    '            <thead>\n' +
                    '              <tr>\n' +
                    '                <th scope="col" style="padding: 10px;">height</th>\n' +
                    '                <th scope="col" style="padding: 10px;">tx_type</th>\n' +
                    '                <th scope="col" style="padding: 10px;">tx_time</th>\n' +
                    '                <th scope="col" style="padding: 10px;">node_address</th>\n' +
                    '                <th scope="col" style="padding: 10px;">block_hash</th>\n' +
                    '                <th scope="col" style="padding: 10px;">tx_id</th>\n' +
                    '                <th scope="col" style="padding: 10px;">previous_tx_id</th>\n' +
                    '              </tr>\n' +
                    '            </thead>\n' +
                    '            <tbody>\n'

                    let i = 0;
                    for(let k in blocks_dict ){
                        let block = blocks_dict[k]
                        query_res_html += '<tr onclick="pop_find_block_detail(this)">\n' +
                    '                <th scope="row" style="padding: 10px;">'+ block.height+'</th>\n' +
                    '                <td style="padding: 10px;">'+ block.tx_type+'</td>\n' +
                    '                <td style="padding: 10px;">'+ block.tx_time+'</td>\n' +
                    '                <td style="padding: 10px; word-break:break-all;">'+ block.node_address+'</td>\n' +
                    '                <td style="padding: 10px; word-break:break-all;">'+ block.block_hash+'</td>\n' +
                    '                <td style="padding: 10px; word-break:break-all;">'+ block.tx_id+'</td>\n' +
                    '                <td style="padding: 10px; word-break:break-all;">'+ block.previous_tx_id+'</td>\n' +
                    '              </tr>\n'
                        i += 1;
                    }
                    query_res_html += '</tbody></table></div>';
                    $('#console-find-query-res-wrap').html(query_res_html);
                }
                else {

                }
            },
            error: function (message) {

            }
        });

    }, 500);
}


function ask_type_num(xtype, get_xtype_num_callback) {
    $.ajax({
        type: "POST",
        url: "./ask_type_num",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({'xtype': xtype}),
        dataType: "json",
        success: function(message) {
            if (message.state === 0) {
                get_xtype_num_callback(message.content);
            }
        },
        error: function(message) {

        }
    });
}


function ask_global_cnrp(height, get_global_cnrp_callback) {
    let height_list = [];
    height_list.push(height);
    $.ajax({
        type: "POST",
        url: "./ask_global_cnrp",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({'height_list': height_list}),
        dataType: "json",
        success: function(message) {
            if (message.state === 0) {
                get_global_cnrp_callback(message.content);
            }
        },
        error: function(message) {

        }
    });
}


function pop_find_block_detail(this_ele){
    let height = $(this_ele).children(':first').text();
    pop_block_detail(height, 'height');
}


function pop_chain_block_detail(this_ele) {
    let height = $(this_ele).children('.lzc_label').children('.side-panel-2-list-padding-right-height-flag').text().split(' ')[1];
    pop_block_detail(height, 'height');
}


function pop_state_block_detail() {
    pop_block_detail(cur_height+'', 'height');
}


function get_block_detail_tables(block_dict) {

    let content_html_wrap = '<div class="blank-line-03"></div>\n' +
            '        <div class="text-center lead console-text-size-04">Block-详细信息</div>\n' +
            '        <div class="blank-line-01"></div>\n'

    return new Promise((resolve, reject) => resolve(
        content_html_wrap + get_block_detail_tables_do(block_dict) + '<div class="blank-line-1"></div>'
    ));
}


function pop_block_detail(attr_value, attr_name) {
    $('#block-detail-panel-lc').fadeIn();
    loading_gif($('#block-detail-panel-content'));
    setTimeout(function () {

        let find_condition = {'block_info_type': 1, 'find_condition': {}}
        find_condition.find_condition[attr_name] = attr_value;

        $.ajax({
            type: "POST",
            url: "./ask_query",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(find_condition),
            dataType: "json",
            success: function (message) {

                let block_dict = message.content[0]

                if (message.state === 0) {
                    get_block_detail_tables(block_dict).then(
                        function (content_html) {
                            $('#block-detail-panel-content').html(content_html);
                        }
                    );
                }
            },
            error: function (message) {

            }
        });

    }, 500);
}


function release_upload() {

    let ask_dict = {
        'upload_data': $('#console-upload-input-data').val(),
        'upload_desc': $('#console-upload-input-desc').val()
    }

    if(ask_dict.upload_data==='' || ask_dict.upload_desc==='') {
        alert('请输入必要字段，不能为空。');
        return;
    }

    loading_gif($('#pills-3'));

    setTimeout(function () {

        $.ajax({
            type: "POST",
            url: "./ask_upload",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(ask_dict),
            dataType: "json",
            success: function (message) {

                if (message.state === 0) {
                    let add_html = '' +
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" style="margin-right: 10px" onclick="console_panel_return(1)">返回Upload</button>'+
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" id="console-upload-good-query" style="margin-left: 10px" onclick="pop_block_detail(\''+message.content+'\', \'tx_id\')">查看该块</button>';
                    // $('#console-upload-good-query').attr('onclick', 'pop_block_detail('+message.content+', "tx_id")');
                    good_gif($('#pills-3'), add_html);
                }

            },
            error: function (message) {

            }
        });

    }, 500);
}


function release_request() {
    let ask_dict = {'data_id': $('#console-request-input-tx-id').val()}
    if(ask_dict.data_id==='') {
        alert('请输入必要字段，不能为空。');
        return;
    }

    loading_gif($('#pills-4'));

    setTimeout(function () {

        $.ajax({
            type: "POST",
            url: "./ask_request",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(ask_dict),
            dataType: "json",
            success: function (message) {

                if (message.state === 0) {
                    let add_html = '' +
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" style="margin-right: 10px" onclick="console_panel_return(2)">返回Request</button>'+
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" id="console-upload-good-query" style="margin-left: 10px" onclick="pop_block_detail(\''+message.content+'\', \'tx_id\')">查看该块</button>';
                    // $('#console-upload-good-query').attr('onclick', 'pop_block_detail('+message.content+', "tx_id")');
                    good_gif($('#pills-4'), add_html);
                }

            },
            error: function (message) {

            }
        });

    }, 500);
}


function release_share() {
    let ask_dict = {'tx_id': $('#console-share-input-tx-id').val()}
    if(ask_dict.tx_id==='') {
        alert('请输入必要字段，不能为空。');
        return;
    }

    loading_gif($('#pills-5'));

    setTimeout(function () {

        $.ajax({
            type: "POST",
            url: "./ask_share",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(ask_dict),
            dataType: "json",
            success: function (message) {

                if (message.state === 0) {
                    let add_html = '' +
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" style="margin-right: 10px" onclick="console_panel_return(3)">返回Share</button>'+
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" id="console-upload-good-query" style="margin-left: 10px" onclick="pop_block_detail(\''+message.content+'\', \'tx_id\')">查看该块</button>';
                    // $('#console-upload-good-query').attr('onclick', 'pop_block_detail('+message.content+', "tx_id")');
                    good_gif($('#pills-5'), add_html);
                }

            },
            error: function (message) {

            }
        });

    }, 500);
}


function release_evaluate() {
    let ask_dict = {'tx_id': $('#console-evaluate-input-tx-id').val(), 'data_score': $('#console-evaluate-input-data-score').val()}
    if(ask_dict.tx_id==='' || ask_dict.data_score==='') {
        alert('请输入必要字段，不能为空。');
        return;
    }

    loading_gif($('#pills-6'));

    setTimeout(function () {

        $.ajax({
            type: "POST",
            url: "./ask_evaluate",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(ask_dict),
            dataType: "json",
            success: function (message) {

                if (message.state === 0) {
                    let add_html = '' +
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" style="margin-right: 10px" onclick="console_panel_return(4)">返回Evaluate</button>'+
                        '<button type="button" class="btn btn-outline-primary console-content-btn-sm" id="console-upload-good-query" style="margin-left: 10px" onclick="pop_block_detail(\''+message.content+'\', \'tx_id\')">查看该块</button>';
                    // $('#console-upload-good-query').attr('onclick', 'pop_block_detail('+message.content+', "tx_id")');
                    good_gif($('#pills-6'), add_html);
                }

            },
            error: function (message) {

            }
        });

    }, 500);
}


function release_unpack() {
    let ask_dict = {'tx_id': $('#console-unpack-input-tx-id').val()}
    if(ask_dict.tx_id==='') {
        alert('请输入必要字段，不能为空。');
        return;
    }

    loading_gif($('#console-unpack-query-res-wrap'));

    setTimeout(function () {

        $.ajax({
            type: "POST",
            url: "./ask_unpack",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(ask_dict),
            dataType: "json",
            success: function (message) {

                let container_ele = $('#console-unpack-query-res-wrap');

                if (message.state === 0) {

                    let content_html_wrap_s = '<div class="blank-line-0"></div>\n' +
                        '      <div class="text-center lead console-text-size-03">拆包成功</div>\n' +
                        '      <div class="blank-line-0"></div><div class="col-12 console-content-padding-10">';

                    let content_html_wrap_e = '<div class="blank-line-1"></div></div>';
                    // console.log(message.content);

                    container_ele.html(content_html_wrap_s + get_block_detail_tables_do(message.content) + content_html_wrap_e);
                }
            },
            error: function (message) {

            }
        });

    }, 1000);
}


function console_panel_return(return_page) {
    if(return_page===1) {
        $('#pills-3').html('<div class="row console-content-padding-10">\n' +
            '        <div class="lead console-text-size-025 console-content-padding-10"><b>上传数据</b>：上传upload类型块</div>\n' +
            '        <div class="col-7 console-content-padding-10">\n' +
            '          <textarea class="form-control console-content-find-input" id="console-upload-input-data" name="upload-input-data" rows="7" type="text" placeholder="准备上传的数据"></textarea>\n' +
            '        </div>\n' +
            '        <div class="col-5 console-content-padding-10">\n' +
            '          <textarea class="form-control console-content-find-input" id="console-upload-input-desc" name="upload-input-desc" rows="7" type="text" placeholder="对左侧数据的描述"></textarea>\n' +
            '        </div>\n' +
            '      </div>\n' +
            '      <div class="row console-content-padding-10">\n' +
            '        <div class="col-4 offset-8 console-content-padding-10">\n' +
            '          <button type="button" class="btn btn-outline-primary console-content-btn-sm" style="float: right" onclick="release_upload()">立即发布</button>\n' +
            '        </div>\n' +
            '      </div>');
    }
    if(return_page===2) {
        $('#pills-4').html('<div class="row console-content-padding-10">\n' +
            '        <div class="lead console-text-size-025 console-content-padding-10"><b>请求数据</b>：发布request类型块</div>\n' +
            '        <div class="col-12 console-content-padding-10">\n' +
            '          <input class="form-control console-content-find-input" id="console-request-input-tx-id" name="request-input-tx-id" type="text" placeholder="准备请求的upload块的tx_id">\n' +
            '        </div>\n' +
            '      </div>\n' +
            '      <div class="row console-content-padding-10">\n' +
            '        <div class="col-6 offset-6 console-content-padding-10">\n' +
            '          <button type="button" class="btn btn-outline-primary console-content-btn-sm" style="float: right" onclick="release_request()">立即发布</button>\n' +
            '          <button type="button" class="btn btn-outline-success console-content-btn-sm" style="float: right; margin-right: 10px;" onclick="console_release_assist(\'console-request-query-res-wrap\', \'request\')">查看可以请求的数据</button>\n' +
            '        </div>\n' +
            '      </div>\n' +
            '      <div class="row console-content-padding-10" id="console-request-query-res-wrap"></div>');
    }
    if(return_page===3) {
        $('#pills-5').html('<div class="row console-content-padding-10">\n' +
            '        <div class="lead console-text-size-025 console-content-padding-10"><b>共享数据</b>：授权本地数据，发布share类型块</div>\n' +
            '        <div class="col-12 console-content-padding-10">\n' +
            '          <input class="form-control console-content-find-input" id="console-share-input-tx-id" name="share-input-tx-id" type="text" placeholder="准备授权的目标请求的tx_id">\n' +
            '        </div>\n' +
            '      </div>\n' +
            '\n' +
            '      <div class="row console-content-padding-10">\n' +
            '        <div class="col-6 offset-6 console-content-padding-10">\n' +
            '          <button type="button" class="btn btn-outline-primary console-content-btn-sm" style="float: right" onclick="release_share()">立即发布</button>\n' +
            '          <button type="button" class="btn btn-outline-success console-content-btn-sm" style="float: right; margin-right: 10px;" onclick="console_release_assist(\'console-share-query-res-wrap\', \'share\')">查看可以请求的数据</button>\n' +
            '        </div>\n' +
            '      </div>\n' +
            '\n' +
            '      <div class="row console-content-padding-10" id="console-share-query-res-wrap"></div>');
    }
    if(return_page===4) {
        $('#pills-6').html('<div class="row console-content-padding-10">\n' +
            '        <div class="lead console-text-size-025 console-content-padding-10"><b>评估数据</b>：对获取的数据打分，发布share类型块</div>\n' +
            '        <div class="col-10 console-content-padding-10">\n' +
            '          <input class="form-control console-content-find-input" id="console-evaluate-input-tx-id" name="evaluate-input-tx-id" type="text" placeholder="准备评估的目标请求的tx_id">\n' +
            '        </div>\n' +
            '        <div class="col-2 console-content-padding-10">\n' +
            '          <input class="form-control console-content-find-input" id="console-evaluate-input-data-score" name="evaluate-input-data-score" type="text" placeholder="对数据的打分：0~100">\n' +
            '        </div>\n' +
            '      </div>\n' +
            '\n' +
            '      <div class="row console-content-padding-10">\n' +
            '        <div class="col-6 offset-6 console-content-padding-10">\n' +
            '          <button type="button" class="btn btn-outline-primary console-content-btn-sm" style="float: right" onclick="release_evaluate()">立即发布</button>\n' +
            '          <button type="button" class="btn btn-outline-success console-content-btn-sm" style="float: right; margin-right: 10px;" onclick="console_release_assist(\'console-evaluate-query-res-wrap\', \'evaluate\')">查看可以评估的块</button>\n' +
            '        </div>\n' +
            '      </div>\n' +
            '\n' +
            '      <div class="row console-content-padding-10" id="console-evaluate-query-res-wrap"></div>\n');
    }
    if(return_page===5) {
        $('#pills-7').html('<div class="row console-content-padding-10">\n' +
            '        <div class="lead console-text-size-025 console-content-padding-10"><b>解析数据</b>：对获取的数据解密拆包，发布evaluate类型块</div>\n' +
            '        <div class="col-12 console-content-padding-10">\n' +
            '          <input class="form-control console-content-find-input" id="console-unpack-input-tx-id" name="unpack-input-tx-id" type="text" placeholder="准备拆包请求的tx_id">\n' +
            '        </div>\n' +
            '      </div>\n' +
            '\n' +
            '      <div class="row console-content-padding-10">\n' +
            '        <div class="col-6 offset-6 console-content-padding-10">\n' +
            '          <button type="button" class="btn btn-outline-primary console-content-btn-sm" style="float: right" onclick="release_unpack()">立即拆包</button>\n' +
            '          <button type="button" class="btn btn-outline-success console-content-btn-sm" style="float: right; margin-right: 10px;" onclick="console_release_assist(\'console-unpack-query-res-wrap\', \'unpack\')">查看可以评估的块</button>\n' +
            '        </div>\n' +
            '      </div>\n' +
            '\n' +
            '      <div class="row console-content-padding-10">\n' +
            '        <div class="col-12 console-content-padding-10" id="console-unpack-res-wrap"></div>\n' +
            '      </div>');
    }
}


function console_release_assist(location_id, page_name) {

    let target_div = $('#'+location_id);
    loading_gif(target_div);

    get_local_node(console_release_assist_callback);

    function console_release_assist_callback(state, local_address) {
        if(state===0){
            let find_condition = {}
            if(page_name==='request') {
                find_condition = {'tx_type': ['upload'], 'node_address': '-'+local_address}
            }
            if(page_name==='share') {
                find_condition = {
                    'tx_type': ['request'],
                    'node_address': local_address,
                    'subject': 'pas'
                }
            }
            if(page_name==='evaluate') {
                find_condition = {
                    'tx_type': ['share'],
                    'node_address': local_address,
                    'subject': 'pas'
                }
            }
            if(page_name==='unpack') {
                find_condition = {
                    'tx_type': ['share'],
                    'node_address': local_address,
                    'subject': 'pas'
                }
            }

            let block_info_type = 0;
            if(page_name==='request') {
                block_info_type = 1
            }

            let condition_dict = {
                'where': 'release_assist',
                'block_info_type': block_info_type,
                'find_condition': find_condition
            }

            setTimeout(function () {

                $.ajax({
                    type: "POST",
                    url: "./ask_query",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(condition_dict),
                    dataType: "json",
                    success: function (message) {

                        if (message.state === 0) {

                            let blocks_dict = message.content;

                            let query_res_html = '';

                            if(page_name==='request') {
                                query_res_html += '<div class="col-12 console-content-padding-10">\n' +
                                '          <table class="table table-hover">\n' +
                                '            <thead>\n' +
                                '              <tr>\n' +
                                '                <th scope="col" style="padding: 10px;">height</th>\n' +
                                '                <th scope="col" style="padding: 10px;">tx_type</th>\n' +
                                '                <th scope="col" style="padding: 10px;">tx_time</th>\n' +
                                '                <th scope="col" style="padding: 10px;">tx_id</th>\n' +
                                '                <th scope="col" style="padding: 10px;">data_describe</th>\n' +
                                '                <th scope="col" style="padding: 10px;">node_address</th>\n' +
                                '              </tr>\n' +
                                '            </thead>\n' +
                                '            <tbody>\n'

                                let i = 0;
                                for(let k in blocks_dict ){
                                    let block = blocks_dict[k]
                                    query_res_html += '<tr onclick="pop_find_block_detail(this)">\n' +
                                '                <th scope="row" style="padding: 10px;">'+ block.height+'</th>\n' +
                                '                <td style="padding: 10px;">'+ block.tx_type+'</td>\n' +
                                '                <td style="padding: 10px;">'+ block.tx_time+'</td>\n' +
                                '                <td style="padding: 10px; word-break:break-all;">'+ block.tx_id+'</td>\n' +
                                '                <td style="padding: 10px; word-break:break-all;">'+ block.data.data_describe+'</td>\n' +
                                '                <td style="padding: 10px; word-break:break-all;">'+ block.node_address+'</td>\n' +
                                '              </tr>\n'
                                    i += 1;
                                }
                            }
                            else {
                                query_res_html += '<div class="col-12 console-content-padding-10">\n' +
                                '          <table class="table table-hover">\n' +
                                '            <thead>\n' +
                                '              <tr>\n' +
                                '                <th scope="col" style="padding: 10px;">height</th>\n' +
                                '                <th scope="col" style="padding: 10px;">tx_type</th>\n' +
                                '                <th scope="col" style="padding: 10px;">tx_time</th>\n' +
                                '                <th scope="col" style="padding: 10px;">tx_id</th>\n' +
                                '                <th scope="col" style="padding: 10px;">node_address</th>\n' +
                                '              </tr>\n' +
                                '            </thead>\n' +
                                '            <tbody>\n'

                                let i = 0;
                                for(let k in blocks_dict ){
                                    let block = blocks_dict[k]
                                    query_res_html += '<tr onclick="pop_find_block_detail(this)">\n' +
                                '                <th scope="row" style="padding: 10px;">'+ block.height+'</th>\n' +
                                '                <td style="padding: 10px;">'+ block.tx_type+'</td>\n' +
                                '                <td style="padding: 10px;">'+ block.tx_time+'</td>\n' +
                                '                <td style="padding: 10px; word-break:break-all;">'+ block.tx_id+'</td>\n' +
                                '                <td style="padding: 10px; word-break:break-all;">'+ block.node_address+'</td>\n' +
                                '              </tr>\n'
                                    i += 1;
                                }
                            }

                            query_res_html += '</tbody></table></div>';
                            target_div.html(query_res_html);
                        }
                        else {

                        }
                    },
                    error: function (message) {

                    }
                });

            }, 10);
        }
        else {
            target_div.html('<div class="blank-line-2"></div><div class="col-12"><div class="lead text-center console-text-size-025">当前未创建本地节点，无法进行发布操作</div>');
        }
    }
}


// --------------------------------------------------------
function get_block_detail_tables_do(block_dict) {
        let content_html = '<table class="table table-hover" style="margin-bottom: 0">\n' +
            '          <thead>\n' +
            '            <tr>\n' +
            '              <th scope="col" style="padding: 10px;">Name</th>\n' +
            '              <th scope="col" style="padding: 10px;">Value</th>\n' +
            '            </tr>\n' +
            '          </thead>\n' +
            '          <tbody>\n';
        for(let i in block_dict){
            content_html += '<tr><th scope="row" style="padding: 10px;">'+ i +'</th><td style="padding: 10px; word-break:break-all;">';

            if ($.type(block_dict[i]) === 'object') {
                content_html += get_block_detail_tables_do(block_dict[i]);
            }
            else {
                content_html += block_dict[i];
                // content_html += '<button class="btn btn-outline-primary console-content-btn-ssm">复制</button></td></tr>';
                content_html += '</td></tr>';
            }
        }
        content_html += '</tbody></table>';
        // console.log(content_html)
        return content_html;
    }



